import React, {Component} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import Modal from 'react-native-modal';

import {Picker} from '@react-native-community/picker';

export default class extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.updateValue(this.props);
  }
  state = {
    show: false,
    lazyValue: null,
  };
  hide() {
    this.setState({
      show: false,
    });
  }
  updateValue(props) {
    const {value, items} = props;
    const {lazyValue} = this.state;
    if (value !== lazyValue) {
      this.setState({
        lazyValue: value,
      });
    }
    if (!value && !lazyValue) {
      this.setState({
        lazyValue: items[0].value,
      });
    }
  }
  UNSAFE_componentWillReceiveProps(newProps) {
    this.updateValue(newProps);
  }
  render() {
    const {value, onValueChange, items = []} = this.props;
    const {lazyValue} = this.state;
    const item = items.find((ele) => ele.value === value);
    return (
      <View style={styles.container}>
        <TouchableOpacity
          onPress={() => {
            this.setState({
              show: true,
            });
          }}>
          {value ? <Text>{item && item.label}</Text> : <Text>請選擇</Text>}
        </TouchableOpacity>
        <Modal isVisible={this.state.show} style={styles.modal}>
          <View style={styles.content}>
            <View style={styles.actionBar}>
              <TouchableOpacity onPress={this.hide.bind(this)}>
                <Text>CANCEL</Text>
              </TouchableOpacity>
              <Text>Picker</Text>
              <TouchableOpacity
                onPress={() => {
                  this.hide();
                  onValueChange && onValueChange(lazyValue);
                }}>
                <Text>OK</Text>
              </TouchableOpacity>
            </View>
            <Picker
              selectedValue={lazyValue}
              onValueChange={(v) => {
                this.setState({
                  lazyValue: v,
                });
              }}>
              {items.map((ele) => {
                return (
                  <Picker.Item
                    key={ele.value}
                    label={ele.label}
                    value={ele.value}
                  />
                );
              })}
            </Picker>
          </View>
        </Modal>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  modal: {
    justifyContent: 'flex-end',
    margin: 0,
  },
  content: {
    backgroundColor: '#fff',
    maxHeight: 400,
  },
  actionBtn: {},
  actionBar: {
    height: 50,
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 10,
  },
});
